const Service = require('egg').Service;

class GoodService extends Service {
    // 创建二手商品
    async create(goodData) {
        const { ctx } = this;

        // 处理图片数据 - 确保存储为合法的字符串格式
        if (goodData.images && Array.isArray(goodData.images)) {
            // 如果是数组，转换为逗号分隔的字符串
            goodData.images = goodData.images.filter(url => url && url.trim()).join(',');
        } else if (goodData.images && typeof goodData.images === 'string') {
            // 已经是字符串，确保是有效的格式
            if (goodData.images.startsWith('[') && goodData.images.endsWith(']')) {
                // 如果是JSON数组字符串，解析后重新转换为逗号分隔
                try {
                    const imageArray = JSON.parse(goodData.images);
                    if (Array.isArray(imageArray)) {
                        goodData.images = imageArray.filter(url => url && url.trim()).join(',');
                    }
                } catch (e) {
                    // 解析失败，保持原样或清空
                    goodData.images = '';
                }
            }
            // 如果是逗号分隔的字符串，保持不变
        } else {
            goodData.images = '';
        }

        // 确保images是有效的字符串
        if (!goodData.images || typeof goodData.images !== 'string') {
            goodData.images = '';
        }

        console.log('创建商品图片数据:', goodData.images);

        // 创建商品
        const good = await ctx.model.Good.create({
            ...goodData,
            created_at: new Date(),
            updated_at: new Date(),
        });

        // 关联卖家信息
        const goodWithSeller = await ctx.model.Good.findByPk(good.item_id, {
            include: [{
                model: ctx.model.User,
                as: 'seller',
                attributes: ['user_id', 'nickname', 'avatar', 'phone']
            }]
        });

        // 将图片字符串转换为数组返回给前端
        return this.formatGoodImages(goodWithSeller);
    }

    // 获取二手商品列表（分页）- 添加模糊搜索支持
    async getGoods(query) {
        const { ctx } = this;
        const { page = 1, pageSize = 10, category, status, minPrice, maxPrice, keyword, ...where } = query;

        const options = {
            where,
            include: [{
                model: ctx.model.User,
                as: 'seller',
                attributes: ['user_id', 'nickname', 'avatar', 'phone']
            }],
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            order: [['created_at', 'DESC']]
        };

        // 模糊搜索 - 支持标题和描述搜索
        if (keyword) {
            options.where = {
                ...options.where,
                [ctx.app.Sequelize.Op.or]: [
                    {
                        title: {
                            [ctx.app.Sequelize.Op.like]: `%${keyword}%`
                        }
                    },
                    {
                        description: {
                            [ctx.app.Sequelize.Op.like]: `%${keyword}%`
                        }
                    }
                ]
            };
        }

        // 分类筛选
        if (category) {
            options.where.category = category;
        }

        // 状态筛选
        if (status !== undefined) {
            options.where.status = parseInt(status);
        }

        // 价格范围筛选
        if (minPrice || maxPrice) {
            options.where.price = {};
            if (minPrice) {
                options.where.price[ctx.app.Sequelize.Op.gte] = parseFloat(minPrice);
            }
            if (maxPrice) {
                options.where.price[ctx.app.Sequelize.Op.lte] = parseFloat(maxPrice);
            }
        }

        const { count, rows } = await ctx.model.Good.findAndCountAll(options);

        // 将图片字符串转换为数组返回给前端
        const processedRows = rows.map(item => this.formatGoodImages(item));

        return {
            list: processedRows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 简单列表（不关联用户信息）- 添加模糊搜索支持
    async getGoodsSimple(query) {
        const { ctx } = this;
        const { page = 1, pageSize = 10, category, status, minPrice, maxPrice, keyword, ...where } = query;

        const options = {
            where,
            attributes: ['item_id', 'title', 'category', 'price', 'images', 'status', 'created_at'],
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            order: [['created_at', 'DESC']]
        };

        // 模糊搜索 - 支持标题和描述搜索
        if (keyword) {
            options.where = {
                ...options.where,
                [ctx.app.Sequelize.Op.or]: [
                    {
                        title: {
                            [ctx.app.Sequelize.Op.like]: `%${keyword}%`
                        }
                    },
                    {
                        description: {
                            [ctx.app.Sequelize.Op.like]: `%${keyword}%`
                        }
                    }
                ]
            };
        }

        // 分类筛选
        if (category) {
            options.where.category = category;
        }

        // 状态筛选
        if (status !== undefined) {
            options.where.status = parseInt(status);
        }

        // 价格范围筛选
        if (minPrice || maxPrice) {
            options.where.price = {};
            if (minPrice) {
                options.where.price[ctx.app.Sequelize.Op.gte] = parseFloat(minPrice);
            }
            if (maxPrice) {
                options.where.price[ctx.app.Sequelize.Op.lte] = parseFloat(maxPrice);
            }
        }

        const { count, rows } = await ctx.model.Good.findAndCountAll(options);

        // 将图片字符串转换为数组返回给前端
        const processedRows = rows.map(item => this.formatGoodImages(item));

        return {
            list: processedRows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 获取用户发布的商品 - 添加模糊搜索支持
    async getUserGoods(userId, query) {
        const { ctx } = this;
        const { page = 1, pageSize = 10, category, status, keyword } = query;

        const options = {
            where: { user_id: userId },
            include: [{
                model: ctx.model.User,
                as: 'seller',
                attributes: ['user_id', 'nickname', 'avatar', 'phone']
            }],
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            order: [['created_at', 'DESC']]
        };

        // 模糊搜索 - 支持标题和描述搜索
        if (keyword) {
            options.where = {
                ...options.where,
                [ctx.app.Sequelize.Op.or]: [
                    {
                        title: {
                            [ctx.app.Sequelize.Op.like]: `%${keyword}%`
                        }
                    },
                    {
                        description: {
                            [ctx.app.Sequelize.Op.like]: `%${keyword}%`
                        }
                    }
                ]
            };
        }

        // 分类筛选
        if (category) {
            options.where.category = category;
        }

        // 状态筛选
        if (status !== undefined) {
            options.where.status = parseInt(status);
        }

        const { count, rows } = await ctx.model.Good.findAndCountAll(options);

        // 将图片字符串转换为数组返回给前端
        const processedRows = rows.map(item => this.formatGoodImages(item));

        return {
            list: processedRows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 根据ID获取商品详情
    async getGoodById(goodId) {
        const { ctx } = this;

        const good = await ctx.model.Good.findByPk(goodId, {
            include: [{
                model: ctx.model.User,
                as: 'seller',
                attributes: ['user_id', 'nickname', 'avatar', 'phone', 'email']
            }]
        });

        if (!good) {
            throw new Error('商品不存在');
        }

        // 将图片字符串转换为数组
        return this.formatGoodImages(good);
    }

    // 更新商品信息
    async updateGood(goodId, updateData) {
        const { ctx } = this;

        // 检查商品是否存在
        const good = await ctx.model.Good.findByPk(goodId);
        if (!good) {
            throw new Error('商品不存在');
        }

        // 处理图片数据 - 确保存储为合法的字符串格式
        if (updateData.images && Array.isArray(updateData.images)) {
            // 如果是数组，转换为逗号分隔的字符串
            updateData.images = updateData.images.filter(url => url && url.trim()).join(',');
        } else if (updateData.images && typeof updateData.images === 'string') {
            // 已经是字符串，确保是有效的格式
            if (updateData.images.startsWith('[') && updateData.images.endsWith(']')) {
                // 如果是JSON数组字符串，解析后重新转换为逗号分隔
                try {
                    const imageArray = JSON.parse(updateData.images);
                    if (Array.isArray(imageArray)) {
                        updateData.images = imageArray.filter(url => url && url.trim()).join(',');
                    }
                } catch (e) {
                    // 解析失败，保持原样
                }
            }
            // 如果是逗号分隔的字符串，保持不变
        }

        // 确保images是有效的字符串
        if (updateData.images && typeof updateData.images !== 'string') {
            delete updateData.images; // 如果不是字符串，删除该字段，不更新
        }

        console.log('更新商品图片数据:', updateData.images);

        // 更新商品信息
        await good.update({
            ...updateData,
            updated_at: new Date()
        });

        // 返回更新后的商品信息（关联卖家）
        const updatedGood = await ctx.model.Good.findByPk(goodId, {
            include: [{
                model: ctx.model.User,
                as: 'seller',
                attributes: ['user_id', 'nickname', 'avatar', 'phone']
            }]
        });

        // 将图片字符串转换为数组
        return this.formatGoodImages(updatedGood);
    }

    // 更新商品状态
    async updateGoodStatus(goodId, status) {
        const { ctx } = this;

        const good = await ctx.model.Good.findByPk(goodId);
        if (!good) {
            throw new Error('商品不存在');
        }

        await good.update({
            status: parseInt(status),
            updated_at: new Date()
        });

        const updatedGood = await ctx.model.Good.findByPk(goodId, {
            include: [{
                model: ctx.model.User,
                as: 'seller',
                attributes: ['user_id', 'nickname', 'avatar', 'phone']
            }]
        });

        // 将图片字符串转换为数组
        return this.formatGoodImages(updatedGood);
    }

    // 删除商品
    async deleteGood(goodId) {
        const { ctx } = this;

        const good = await ctx.model.Good.findByPk(goodId);
        if (!good) {
            throw new Error('商品不存在');
        }

        await good.destroy();
        return true;
    }

    // 辅助方法：格式化商品图片数据 - 修复base64处理
    formatGoodImages(good) {
        const goodData = good.toJSON ? good.toJSON() : good;

        if (goodData.images && typeof goodData.images === 'string') {
            // 如果是逗号分隔的字符串，转换为数组
            if (goodData.images.includes(',')) {
                goodData.images = goodData.images.split(',').filter(url => {
                    if (!url || !url.trim()) return false;

                    // 验证base64 URL格式
                    if (url.startsWith('data:image/')) {
                        return url.includes('base64,') && url.length > 100;
                    }

                    return true;
                });
            }
            // 如果是单个URL字符串，包装为数组
            else if (goodData.images.trim()) {
                const url = goodData.images.trim();
                if (url.startsWith('data:image/')) {
                    if (url.includes('base64,') && url.length > 100) {
                        goodData.images = [url];
                    } else {
                        goodData.images = [];
                    }
                } else {
                    goodData.images = [url];
                }
            }
            // 空字符串或其他情况
            else {
                goodData.images = [];
            }
        } else if (!goodData.images) {
            goodData.images = [];
        }

        return goodData;
    }
}

module.exports = GoodService;